import pandas as pd
import ast
import loadBugWorkload

taskStatusMap = {
    "60418b08c679e20044c09c0c": "其他功能解决",
    "64af9ca33bb6c5ae1239f98e": "待开发评估",
    "654da2f56c338454318df4de": "待发布SIT(组内环境已测)",
    "5e0dabc57d161c00217800b8": "开发中",
    "6604cf0816117c37565adb54": "待开发",
    "5e0db98a8fc7b60022d301c6": "待组内评审",
    "6535cfab96d44880e05a51b1": "待测试",
    "6535cfab96d44880e05a51b4": "测试中",
    "5f40cf2267d6500044ec1a29": "待分析",
    "6535cfab96d44880e05a51b7": "已发布SIT(合入release部署)",
    "5e0dabc57d161c00217800b9": "已发布生产",
    "614407e924ae43003fd05019": "已完成（不发版）",
    "603ddbf166272e0044b3d934": "已发布UAT",
    "5e0dabc57d161c00217800b7": "待产品内审",
    "5e0db97739a39700233b0199": "待审阅",
    "6340edfabb167700408b7339": "经评估无法实现",
    "65e80e978ec65144610baca1": "待架构组评审",
}
dev_day_benchmark = {
    202501: 16,
    202502: 16,
    202503: 16,
    202504: 16,
    202505: 16,
    202506: 16,
}
sprintMap = {
    "202412-2": "202501",
    "202501-1": "202501",
    "202501-2": "202502",
    "202502-1": "202502",
    "202502-2": "202503",
    "202503-1": "202503",
    "202503-2": "202504",
    "202504-1": "202504",
    "202504-2": "202505",
    "202505-1": "202505",
    "202505-2": "202506",
    "202506-1": "202506",
    "202506-2": "202507",
    "202507-1": "202507",
    "202507-2": "202508",
    "202508-1": "202508",
    "202508-2": "202509",
    "202509-1": "202509",
    "202509-2": "202510",
    "202510-1": "202510",
    "202510-2": "202511",
    "202511-1": "202511",
    "202511-2": "202512",
    "202512-1": "202512",
    "202512-2": "202601",
    "202601-1": "202601",
    "202601-2": "202602",
}


def convertCustomFields(customfieldsStr):
    custom_fields = []
    try:
        real_list = ast.literal_eval(customfieldsStr)
        if isinstance(real_list, list):
            custom_fields = real_list
        else:
            print(f"Warning: String '{customfieldsStr}' did not evaluate to a list.")
    except (SyntaxError, ValueError):
        print(f"Error: Could not parse string '{customfieldsStr}' as a Python literal.")
    return custom_fields


def formatData(data):
    tasks = []
    fatherTasksId = []
    for d in data:
        if "parentTaskId" in d and d["parentTaskId"] not in fatherTasksId:
            fatherTasksId.append(d["parentTaskId"])
    for d in data:
        if taskStatusMap.get(d["tfsId"], "unknow") not in [
            "已发布生产",
            "已完成（不发版）",
        ]:
            continue
        if "executorName" in d:
            customFields = convertCustomFields(d["customfields"])
            task = {
                "id": d["id"],
                "taskNo": "DB-" + str(d["uniqueId"]),
                "executorName": d["executorName"],
                "sprintName": d["sprintName"],
                "publishSprint": sprintMap.get(d["sprintName"], "unknow"),
                "status": taskStatusMap.get(d["tfsId"], "unknow"),
                "parentId": d.get("parentTaskId", None),
                "isFather": d["id"] in fatherTasksId,
            }
            task["frontend"] = "未分配"
            task["backend"] = "未分配"
            task["test"] = "未分配"
            task["frontend_day"] = 0
            task["backend_day"] = 0
            task["test_day"] = 0
            for cf in customFields:
                if cf.get("value", None) is None:
                    continue
                if len(cf["value"]) == 0:
                    continue
                if cf["cfId"] == "660be84c797f388d73107b34":
                    task["frontend"] = cf["value"][0]["title"]
                elif cf["cfId"] == "660be86cfdae364d32426542":
                    task["backend"] = cf["value"][0]["title"]
                elif cf["cfId"] == "660be8a675863a6977f65356":
                    task["test"] = cf["value"][0]["title"]
                elif cf["cfId"] == "62de3ebad7ab965fbdf6c144":
                    task["frontend_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "62de3ed2d51a977b23f42b6b":
                    task["backend_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "62de3ee92d8f775082f164f8":
                    task["test_day"] = float(cf["value"][0]["title"])
            tasks.append(task)
    return tasks


def defineZodiac(row):
    level = "undefined"
    if row["gap"] >= 6 and row["gap"] < 10:
        level = "silver"
    elif row["gap"] >= 10:
        level = "gold"
    elif row["gap"] >= 0:
        level = "bronze"
    return level


def calcGap(row, benchMarks):
    benchmark = benchMarks.get(row["publishSprint"], 999)
    if benchmark == 999:
        return 0
    return row["total_workload"] - benchmark


def getBugWorkload(row, bug_data):
    bug_workload = 0
    for bug in bug_data:
        if str(bug["publishSprint"]) == str(row["publishSprint"]) and str(
            bug["developer"]
        ) == str(row["developer"]):
            bug_workload += bug["workload"]
    return bug_workload


def summaryByRole(df, bug_data, role_name, workload_name):
    result_df = (
        df.groupby(["publishSprint", role_name])[workload_name]
        .sum()
        .to_frame(name="task_workload")
        .reset_index()
        .rename(columns={role_name: "developer"})
    )

    result_df["role"] = role_name
    result_df["bug_workload"] = result_df.apply(
        getBugWorkload, axis=1, args=(bug_data,)
    )
    result_df["total_workload"] = result_df["task_workload"] + result_df["bug_workload"]
    result_df["gap"] = result_df.apply(calcGap, axis=1, args=(dev_day_benchmark,))
    result_df["level"] = result_df.apply(defineZodiac, axis=1)
    return result_df


def calcGapByProducter(row, benchMarks):
    benchmark = 999
    for b in benchMarks:
        if b.get("publishSprint", 99999) == row["publishSprint"]:
            benchmark = b.get("prd_bk_day")
            break
    if benchmark == 999:
        return 0

    return row["total_workload"] - benchmark


def summaryProducter(df, bug_data, bk_df):
    prd_benchMark = bk_df.to_dict("records")
    producter_df = (
        df.groupby(["publishSprint", "producter"])["producter_day"]
        .sum()
        .to_frame(name="task_workload")
        .reset_index()
        .rename(columns={"producter": "developer"})
    )
    producter_df["role"] = "producter"
    producter_df["bug_workload"] = producter_df.apply(
        getBugWorkload, axis=1, args=(bug_data,)
    )
    producter_df["total_workload"] = (
        producter_df["task_workload"] + producter_df["bug_workload"]
    )
    producter_df["gap"] = producter_df.apply(
        calcGapByProducter, axis=1, args=(prd_benchMark,)
    )
    producter_df["level"] = producter_df.apply(defineZodiac, axis=1)
    return producter_df


def getWorkload():
    bug_data = loadBugWorkload.load()
    tasks_df = pd.read_csv("./output/detailData.csv")
    # 过滤掉父需求
    tasks_df = tasks_df[tasks_df["isFather"] == False]
    product_bk_df = (
        tasks_df.groupby(["publishSprint"])["producter_day"]
        .sum()
        .to_frame(name="prd_bk_day")
        .reset_index()
    )
    product_bk_df["prd_bk_day"] = product_bk_df["prd_bk_day"] / 10
    frontend_df = summaryByRole(tasks_df, bug_data, "frontend", "frontend_day")
    backend_df = summaryByRole(tasks_df, bug_data, "backend", "backend_day")
    test_df = summaryByRole(tasks_df, bug_data, "test", "test_day")
    producter_df = summaryProducter(tasks_df, bug_data, product_bk_df)
    return pd.concat([frontend_df, backend_df, test_df, producter_df])


def testfn():
    df = getWorkload()

    print(
        df[
            # (df["gap"] > 0)
            (df["publishSprint"] == 202505)
            & (df["role"] == "producter")
        ].head(20)
    )


# testfn()
